// 导入数据库操作模块
const { mysql } = require("../../db/index");
const moment = require("moment");
const { filesURL } = require("../../../config");
const bcrypt = require("bcryptjs");

// 获取当前用户信息
exports.Info = async (req, res) => {
	try {
		const sqlStr = "SELECT id,nickname,username,roles,email,gender,register,avatar,age FROM userinfo WHERE id = ? ";
		const [results] = await mysql.query(sqlStr, [req.user.id]);
		if (results.length === 0) return res.error("暂无用户信息!");

		const data = {
			...results[0],
			avatar: `${filesURL}/images/avatar/${results[0].avatar}`,
			register: moment(results[0].register).format("YYYY-MM-DD HH:mm:ss"),
		};

		return res.success(data);
	} catch (err) {
		return res.error(err);
	}
};

exports.Update = async (req, res) => {
	const { nickname, email, gender } = req.body;

	try {
		const sqlStr = "update userinfo set nickname = ? , email = ? , gender = ? where id = ?";
		const [results] = await mysql.query(sqlStr, [nickname, email, gender, req.user.id]);
		if (results.affectedRows !== 1) return res.error("更新失败");
		return res.success("更新成功");
	} catch (err) {
		return res.error(err);
	}
};

exports.ResetPwd = async (req, res) => {
	try {
		const sqlStr1 = "select * from userinfo where id = ?";
		const [results1] = await mysql.query(sqlStr1, [req.user.id]);
		if (results1.length !== 1) return res.error("用户不存在!");

		// 判断用户输入的旧密码是否正确
		const compareResult = bcrypt.compareSync(req.body.oldPwd, results1[0].password);
		if (!compareResult) return res.error("旧密码错误!");

		const sqlStr2 = "update userinfo set password = ? where id = ?";
		// 对新密码进行加密处理
		const newPwd = bcrypt.hashSync(req.body.newPwd, 10);

		const [results2] = await mysql.query(sqlStr2, [newPwd, req.user.id]);
		if (results2.affectedRows !== 1) return res.error("密码更新失败!");
		return res.success("密码更新成功!");
	} catch (err) {
		return res.error(err);
	}
};

exports.AvatarUpload = async (req, res) => {
	try {
		const sqlStr = "UPDATE userinfo SET avatar = ? where id = ?";
		const [results] = await mysql.query(sqlStr, [req.body.avatar, req.user.id]);
		if (results.affectedRows !== 1) return res.error("头像更新失败！");
		return res.success("头像更新成功");
	} catch (err) {
		return res.error(err);
	}
};